<template>
  <div class="common-form">
    <common-form :formConfig="formConfig" @input="onFormUpdated"></common-form>
    <div class="form-operation">
      <button class="form-btn btn-primary" :class="{'btn-disable':publishing}" @click="doSubmit(1)">发布</button>
      <button class="form-btn" @click="doSubmit(0)" v-if="!hasPublish">存草稿</button>
      <button class="form-btn" :class="{'btn-disable':publishing}"  @click="doPreview">预览</button>
      <button class="form-btn" :class="{'btn-disable':publishing}"  @click="doCancel">取消</button>
    </div>
  </div>
</template>

<script>
import CommonForm from '../../../form/CommonForm.vue';
import * as types from 'store/mutation-types';

export default {
  name: 'article',
  components:{
    "common-form":CommonForm
  },
  data() {
    let editingData = this.$store.state.article.editingData;
    return {
      formData: {},
      validate: {},
      previewPopup: null,
      contentId: editingData.id,
      formConfig: [{
        name: 'title',
        title: '文章标题',
        desc: '请输入文章标题，4-44个字符(一个中文汉字或符号算两个字符)',
        require: true,
        type: 'text',
        value: editingData.title,
        extra: {
          placeHolder: '4-44个字符',
          limit: [4, 44, 1]
        }
      },{
        name: 'content',
        title: '文章内容',
        desc: '最多40000个字符',
        require: true,
        type: 'editor',
        value: editingData.content
      }, {
        name: 'imageUrl',
        title: '文章封面',
        require: true,
        type: 'cover',
        value: editingData.imageUrl,
        extra: {
          fileDesc: '建议尺寸686*300,大小不超过2M',
          maxFileSize:2*1024*1024,
          width: 686,
          height: 300,
          viewWidth:130,
          viewHeight:95
        }
      }, {
        name: 'previewAllowed',
        title: '是否试读',
        desc: '',
        require: true,
        type: 'radio',
        extra: {
          radio:[{
            key: 1,
            text: '允许',
            checked: true
          },{
            key: 0,
            text: '禁止',
            checked: true
          }]
        },
        value: editingData.previewAllowed
      }],
      publishing: false,
      submit: false
    };
  },
  computed: {
    hasChange: {
      cache: false,
      get() {
        let changed = 0;
        this.formConfig.forEach((item) => {
          let formItem = this.formData[item.name];
          if (formItem && formItem !== item.value) {
            changed++;
          }
        });
        return changed;
      }
    },
    hasPublish() {
      let status = this.$store.state.article.editingData.status;
      //console.log(this.$store.state.article.editingData);
      if(!status){
        return false;
      }
      return status == 2;
    },
    specialColumnId() {
      return this.$route.params.id;
    },
    coursePacketId() {
      return this.$route.params.issue
    }
  },
  methods: {
    onFormUpdated({formData, validate, byUser}) {
      this.formData = formData;
      this.validate = validate;
    },
    doSubmit(flagType) {
      if (!this.publishing) {
        for (let i = 0; i < this.formConfig.length; i++) {
          let config = this.formConfig[i];
          let validate = this.validate[config.name];
          if (!validate.ok) {
            this.$store.dispatch('alert', `${config.title}${validate.info}`);
            return false;
          }
        }
        this.publishing = true;
        this.formData.coursePacketId = this.coursePacketId;
        this.formData.flag = flagType;//保存还是发布标识, 0|保存,1|发布

        this.$store.dispatch('articleSetTempData',this.formData);
        this.$store.dispatch('publishArticle').then(() => {
          this.clearValue();
          this.submit = true;
          this.publishing = false;

          this.$router.push(`/columns/journal/${this.specialColumnId}/${this.coursePacketId}/list`);
        }, () => {
          this.publishing = false;
        });
      }
    },
    doPreview() {
      let delay = 0;
      if (this.previewPopup == null || this.previewPopup.closed) {
        let viewWidth = 900;
        let viewHeight = 800;
        let offsetLeft = (window.screen.availWidth - viewWidth)/2;
        let offsetTop = (window.screen.availHeight - 30 - viewHeight)/2;
        let url = C_OPEN + '/mob/static/column/preview.htm?type=4&project=static&id=' + this.contentId;
        this.previewPopup = window.open(url,"",`height=${viewHeight},width=${viewWidth},top=${offsetTop},left=${offsetLeft},status=no,toolbar=no,menubar=no,location=no`);
        delay = 1500;
      }
      setTimeout(() => {
        this.previewPopup.postMessage({
          id: this.contentId,
          title: this.formData.title,
          content: this.formData.content,
          imageUrl: this.formData.imageUrl,
          previewAllowed: this.formData.previewAllowed
        }, C_OPEN);
        this.previewPopup.focus();
      }, delay);
    },
    doCancel() {
      this.$router.push(`/columns/journal/${this.specialColumnId}/${this.coursePacketId}/list`);
    },
    clearValue() {
      this.formConfig.forEach((input) => {
        input.value = null;
      });
    }
  },
  beforeRouteEnter(to, from, next){
    next(vm => {
      if (vm.$store.state.user.status !== 1) {
        vm.$router.push('/columns')
      }
    })
  },
  beforeRouteLeave(to, from, next) {
    if (!this.submit && this.hasChange > 0){
      this.$store.dispatch('confirm', '您已输入的内容将会丢失，是否确定？').then(()=> {
        this.$store.commit(types.CLEAR_EDIT_STATE);
        this.previewPopup && this.previewPopup.close();
        next();
      }, ()=> {
        next(false);
      })
    }else{
      this.$store.commit(types.CLEAR_EDIT_STATE);
      this.previewPopup && this.previewPopup.close();
      next();
    }
  }
};
</script>

<style lang="less" rel="stylesheet/less">
.common-form{
  .top-nav{
    height: 40px;
    margin-bottom: 30px;
    border-bottom: 1px solid #2e9057;
    .nav-title{
      font-size: 20px;
      color: #2e9057;
    }
  }
}
</style>
